package com.zhanghu.backendZray.utils.file;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 缩略图工具类
 * @author ZhangDong
 * @date 2024/8/17 17:01
 */
public class ThumbnailGenerator {

    /**
     * 创建缩略图
     * @param inputStream
     * @param thumbnailFile 写进这个文件里
     * @param width
     * @param height
     * @throws IOException
     */
    public static void generateThumbnail(InputStream inputStream, File thumbnailFile, int width, int height) throws IOException {
        // 有次启动脚本设置的最大堆32MB，然后上传多张文件，这个方法直接引发OOM。
        BufferedImage originalImage = ImageIO.read(inputStream);
        BufferedImage thumbnail = createThumbnail(originalImage, width, height);
        // Write the thumbnail to a file
        boolean result = ImageIO.write(thumbnail, "jpg", thumbnailFile);
        if (!result) {
            throw new IOException("Could not write the thumbnail to the file.");
        }
    }

    private static BufferedImage createThumbnail(BufferedImage originalImage, int width, int height) {
        // Create a new image with the specified size
        // BufferedImage.TYPE_INT_RGB
        BufferedImage thumbnail = new BufferedImage(width, height, originalImage.getType());
        // Get Graphics2D object and draw the original image onto the new image
        Graphics2D graphics = thumbnail.createGraphics();
        graphics.drawImage(originalImage, 0, 0, width, height, null);
        graphics.dispose();
        return thumbnail;
    }

}
